package model;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserMapper {
    //通过用户名的方式查找用户信息
    public static User selectByName(String userName) throws SQLException {
        Connection connection=null;
        PreparedStatement statement=null;
        DatabaseOperator databaseOperator=new DatabaseOperator();
        connection=databaseOperator.getConnection();


        String sql="select*from user where username=?";
        statement=connection.prepareStatement(sql);
        statement.setString(1,userName);
        //statement=connection.prepareStatement(sql);

        ResultSet resultSet=statement.executeQuery();
        if(resultSet!=null&& resultSet.next()){
            User user=new User();
            user.setUserId(resultSet.getInt("userId"));
            user.setUserName(resultSet.getString("userName"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
        databaseOperator.close(connection,statement,resultSet);
        //数据库中未找到相关用户名的用户
        return null;
    }

    //通过用户名来进行用户查找
    public static User selectByUserId(int userId) throws SQLException {
        Connection connection=null;
        PreparedStatement statement=null;
        DatabaseOperator databaseOperator=new DatabaseOperator();
        connection=databaseOperator.getConnection();

        String sql="select*from user where userId=?";
        statement=connection.prepareStatement(sql);
        statement.setInt(1,userId);

        ResultSet resultSet= statement.executeQuery();
        if(resultSet!=null&& resultSet.next()){
            User user=new User();
            user.setUserId(resultSet.getInt("userId"));
            user.setUserName(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            return user;
        }
        databaseOperator.close(connection,statement,resultSet);
        return null;
    }



}
